/**
 * 首页管理
 */
$(function() {
	
	//初始化 
	initCheckLoginState();
	initfindDoctorDiseaseList();
	initfindSliderList();
	initfindIndexArticleList();
	queryMyDoctorList();
	
	/*获取 疾病列表 接口*/
	function initfindDoctorDiseaseList(){
		var param = {"pageNo":1};
		function callBackFindDoctorDiseaseList(data){
			console.log(data);
			var html = "";
			for (i in data.diseaseList) {
				html +="<div v="+data.diseaseList[i].disname+"><span>"+data.diseaseList[i].disname+"</span></div>";
			}
			$(".question-doctor").append(html);
		}
		homepageModule.findDoctorDiseaseList(param,callBackFindDoctorDiseaseList);
	}
	
	
	// 专属医生
	function queryMyDoctorList() {
		var params = {
			"patientid":USERID	
		};
		userCenterModule.queryMyDoctorList(params, function(callBack) {
			//console.log(callBack.length);
			if(callBack.length){
				for(i=0;i<callBack.length;i++){
					var infors = callBack[i].doctor;
					console.log(infors);	
					if(infors.isfinevisit==0){
						var infor = infors;
						$(".add-doctor").hide();
						var showhtml= "";
						//showhtml+="<div class=\"ask font1\"><a class=\"ask-doctor\" v="+infor.id+" z="+infor.imisopen+" p="+infor.imprice+" detail="+infor.realname+"-图文咨询:"+infor.hospitalName+">问医生</a></div>";
						showhtml+="<div id='doctor-infor'>";
						showhtml+="<div class=\"picture\"><img src=" +infor.avatar+ "></div>";
						showhtml+="<p class=\"doctorinfors font3\"><font class=\"name\">"+infor.realname+"</font> <font class=\"technical-offices\">"+infor.deptName+"</font></p>"
						showhtml+="<p class=\"doct font3\"><font class=\"doctortitle\">"+infor.doctortitle+"</font></p>";
						showhtml+="<p class=\"hospital font3\">"+infor.hospitalName+"</p>";
						var $skilful =infor.skilful;
						if(infor.skilful==undefined) {
							$skilful = " ";
						}
						showhtml+="<p class=\"skilful font3\">擅长:"+$skilful+"</p>";
						//showhtml+="<p class=\"skilful font3\">擅长:"+infor.skilful+"</p>";
						showhtml+="<div class=\"info font1\">";
							showhtml+="<p class='textC'>服务患者端次数:<span class=\"servicetimes\">"+infor.servicetimes+"</span></p>";
							showhtml+="<p class='textC'>关注人数:<span class=\"attention-num\">"+infor.concernnumber+"</span></p>";
						showhtml+="</div>";
						showhtml+="</div>";
						$(".doctor-infor").html(showhtml);
						$(".exclusive-doctor").on("click",".doctor-infor",function(event){
							event.stopPropagation();
							location.replace('html/doctor/doctor-details.html?doctorid='+infor.id);
						});
						$(".ask").on("click",".ask-doctor",function(event){
							event.stopPropagation();
							var imopen = $(this).attr("z");
						 	if(imopen==0){
						 		mui.alert("该医生暂未开通图文咨询服务");
						 	}else{
								var doctorid=$(this).attr("v");
								var imprice=$(this).attr("p");
								var detail=$(this).attr("detail");
								var doctorid=$(this).attr("v");
								var consultOrder={};
								consultOrder.doctorid=doctorid;
								consultOrder.payAmount=imprice;
								consultOrder.orderDetail=detail;
								consultOrder.orderType=1;
								
								var result=checkUnfinishedOrder(USERID,doctorid);
								if(result==true){
								   var orderKey="doctor_index";
								   sessionStorage.setItem(orderKey,JSON.stringify(consultOrder));
								   location.replace("html/onlineContinuation/medication-consultation.html?doctorId="+doctorid);
								}else{
									return false;
								}
							
							}
						});
					}
				}
			}
		});
	}
	
	$(".add-doctor").on("click",function(){
		mui.alert("请使用微信扫一扫,添加您的专属医生",'提示');
	});
	//选择症状信息
	$(".question-doctor").on("click","div", function(e) {
		var diseaseId = $(this).attr("v");
		diseaseId = escape(diseaseId)
	  	location.href ="html/doctor/doctor-list.html?realname=" + diseaseId;
	  	sessionStorage.setItem("doctorZz",JSON.stringify(1));
	});
	
	/*获取 轮播图 接口*/
	function initfindSliderList(){
		var param = "";
		function callBackSlider(data){
			console.log(data);
			var html1 = "";
			var html2 = "";
			html1 += '<div class="mui-slider-item  mui-slider-item-duplicate" v="'+data[data.length-1].linkurl+'"><img src="'+data[data.length-1].imgurl+'"></div>';
			for (i in data) {
				html1 += '<div class="mui-slider-item" v="'+data[i].linkurl+'"><img src="'+data[i].imgurl+'"></div>';
				html2 += '<div class="mui-indicator"></div>';
			}
			html1 += '<div class="mui-slider-item  mui-slider-item-duplicate" v="'+data[0].linkurl+'"><img src="'+data[0].imgurl+'"></div>';
			$(".mui-slider-group").append(html1);
			$(".mui-slider-indicator").append(html2);
			$($(".mui-indicator")[0]).addClass("mui-active");
		}
		homepageModule.findSliderList(param,callBackSlider);
	}
	
	/*首页轮播图*/
	var gallery = mui('.mui-slider');
	gallery.slider({
		interval:5000//自动轮播周期，若为0则不自动播放，默认为0；
	}); 
	
	$(".mui-slider-group .mui-slider-item").click(function(){
		var bannerLink = $(this).attr("v");
		location.href = bannerLink;
	});
	
	/*获取文章列表 接口*/
	function initfindIndexArticleList(){
		var param = {"pageSize":3};
		var html="";
		function callBackArticle (data){
			for(i in data){
				var datetime =data[i].createtime;
				var date=datetime.substring(0,10);
				var dates=date.split("-");
				var $datetime = dates[1]+'月'+dates[2]+'日';
				
				html += '<div class="daily-guide" v="'+data[i].id+'" type="'+data[i].typeid+'">'
					+ '<img src="'+data[i].thumbnailurl+'">'
					+ '<span class="mui-ellipsis-2 font3 read-title">'+data[i].title+'</span>'
					+ '<p class="font1">'+$datetime+'</p>'
					+ "</div>"
			}
			$("#day_guidance").append(html);
		}
		homepageModule.findIndexArticleList(param,callBackArticle);
	}
	$(".daily-guide").click(function(){
		var articleId = $(this).attr("v");
		//var typeId = $(this).attr("type");
		location.href ="html/article/article-detail.html?articleId="+articleId;
	});
	
	
	
	/**
 * 检查患者与医生的未完成订单信息
 * 引用commonService.js,并直接在业务模块调用该方法，返回true，则return false;
 * @param {Object} userid
 * @param {Object} doctorid
 */
function checkUnfinishedOrder(userid, $doctorid) {
	var result = true;
	if($doctorid == null) {
		mui.alert("医生id不能为空!");
		return false;
	}
	var params = {
		userid: userid == null ? USERID : userid,
		doctorid: $doctorid
	}
	utilModule.get({
		url: "consultOrderPay/queryUnfinishedOrderByUid",
		data: params,
		needJson: false,
		async: false,
		success: function(responseObject) {
			console.log(responseObject);
			/**如果有未完成信息，则提示跳转聊天界面 **/
			if(utilModule.checkUndefined(responseObject.id) != "") {
				result=false;
				console.log(responseObject);
				var btnArray = ['否', '是'];
				mui.confirm('您有与该医生有一条未完成咨询记录，去咨询？', '提示', btnArray, function(e) {
					if(e.index == 1) {
						invokeIm(responseObject, $doctorid);
					}
				});
				
			}
		}
	});
	return result;

}

/**
 *  获取医生基本信息并跳转IM
 * @param {Object} data
 */
function invokeIm(data, $doctorid) {
	var orderid = data.id;
	//咨询类型：1:快速提问      2:图文   3:用药咨询
	 // 图文：2   用药: 5
	var orderType = data.orderType;
	if(orderType==2){
		payStatus = 2
	}
	if(orderType==3){
		payStatus = 5
	}
	var params = {
		"doctorId": $doctorid
	};
	utilModule.post({
		url: "doctor/doctorDetail",  //医生详情页
		data: params,
		needJson: false,
		async: false,
		success: function(response) {
			console.log(response);
			var result = response;
			if(result != null) {
				var doctorInfo = result.doctor;
				var doctorObject = {};
				var usernameIM = DOCTOR_IM_PREFFIX + doctorInfo.id;
				
				doctorObject.doctorid = doctorInfo.id;
				doctorObject.usernameIM = usernameIM;
				doctorObject.avatar = doctorInfo.avatar;
				doctorObject.realname = doctorInfo.realname;
				doctorObject.deptName = doctorInfo.deptName;
				utilModule.setStorage(usernameIM, JSON.stringify(doctorObject));
				
				mui.toast("正在跳转咨询界面....");
				console.log("医生信息:" + utilModule.getStorage(usernameIM));
				//支付成功跳转im聊天界面  
				
				location.replace("html/inquiry/inquiry-service.html?usernameIM=" + usernameIM + "&orderid=" + orderid + "&payStatus="+payStatus+"&doctorid=" + doctorInfo.id);
			}
		}
	});
}

	/**
	 * 1.判断是否授权登录，如果未授权，则跳转微信授权
	 * 2.是否为扫描关注链接，如果授权，则自动关注该医生
	 */
	function initCheckLoginState() {
		
		//判断是否为医生二维码地址
		var doctorid=utilModule.getQueryString("doctorid");
		var redirect_uri="/n/loginRedirect.html";
		if(OPENID == null) {
		   if(doctorid!=null){
			  redirect_uri= utilModule.encodeURIComponent(redirect_uri+"?doctorid="+doctorid);
			}
			location.replace(serverUrl + "homepage/oauth?scopeType=1&redirect_uri="+redirect_uri);
		}else{
		   if(doctorid!=null){
		   	  addDoctorFirend(doctorid);
			}
		}
	}
	
	/**
	 * 接收通过微信扫一扫直接加关注
	 * @param {Object} _doctorid
	 */
	function addDoctorFirend(_doctorid){
	    console.log("doctorid:"+_doctorid);
	    var params={};
	    params.doctorid=_doctorid;
	    params.patientid=USERID;
	    
	    //判断该医生是否真实存在
	    var doctorInfo=queryDoctorInfo(_doctorid);
	    if(doctorInfo==null){
	        mui.alert("关注失败，二维码可能已失效！","提示");	
	        return false;
	    }else{
       	  userCenterModule.addDoctorFirend(params, function(callBack) {
	    	var result=callBack;
	    	if(result.status==200){
	    	    mui.alert("恭喜您成功扫描"+doctorInfo.realname+"医生为您的专属医生!","提示",function(){
	    		  queryMyDoctorList();
	    	    });
	    	}else{
	    	   mui.alert(result.msg,"提示");
	    	}
			});
	    }
	}
	
	
	  /**
   * 获取医生详情
   * @param {Object} $doctorid
   */
   function queryDoctorInfo($doctorid){
  	 var params = {
		"doctorId": $doctorid
	};
	var doctorInfo=null;
	utilModule.post({
		url: "doctor/doctorDetail",  //医生详情页
		data: params,
		needJson: false,
		async: false,
		success: function(response) {
			console.log(response);
			var result = response;
			if(result != null) {
				  doctorInfo = result.doctor;
			}
		}
	});
	return doctorInfo;
  }
	
	
	$(".html-loding").hide();
	
	document.getElementById("index").addEventListener('tap',function(){
		mui.openWindow({
			url:'index.html',
    		id:'index',
		});
	});
	document.getElementById('message').addEventListener('tap',function(){
		mui.openWindow({
			url:'html/inquiry/message-list.html',
    		id:'message',
		});
	});
	document.getElementById('article').addEventListener('tap',function(){
		mui.openWindow({
			url:'html/article/article-list.html',
    		id:'article',
		});
	});
	document.getElementById('userCenter').addEventListener('tap',function(){
		mui.openWindow({
			url:'html/userCenter/user-center.html',
    		id:'userCenter',
		});
	});
});

